package com.hp.search_service.listener;

import com.hp.common_api.entity.Spu;
import com.hp.search_service.config.RabbitMQConfig;
import com.hp.search_service.entity.Goods;
import com.hp.search_service.feign.GoodsFeignClient;
import com.hp.search_service.repository.GoodsRepository;
import com.hp.search_service.service.GoodsIndexService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoodsListener {

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @Autowired
    private GoodsIndexService goodsIndexService;

    @Autowired
    private GoodsRepository goodsRepository;

    //绑定进行添加操作的消息
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMQConfig.QUEUE_GOODS_SAVE,durable = "true"),
                    exchange = @Exchange(value = RabbitMQConfig.GOODS_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    ,key = RabbitMQConfig.KEY_GOODS_SAVE)})
    public void receiveGoodsSave(Long id){
        System.out.println("接受到id" + id);
        //通过spuId查询商品
        Spu spu = goodsFeignClient.getSpuById(id).getBody();
        //将spu转换为Goods
        Goods goods = goodsIndexService.createGoodsFromSpu(spu);
        //添加到ES中
        goodsRepository.save(goods);
        System.out.println("商品同步完成：" + goods);
    }
}
